# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : handle_dingding.py
# Time       ：2023/7/6 13:35
# Author     ：周豪权
"""
import os
import json
import requests
import jenkins




class send_ding:
    last_build_number: int

    #连接jenkins获取job的number
    def job_num(self):
        jk = jenkins.Jenkins(url='http://172.26.161.55:8888', username='zhouhaoquan',password='113ae368dc1dfc1475d47e644abebbeee9')
        last_build_number = jk.get_job_info('SEM')['lastBuild']['number']
        return last_build_number


    def send_ding(self):
        base_path = os.path.dirname(os.path.dirname(__file__))
        file_name = os.path.join(base_path,'reports','widgets','summary.json')
        with open(file_name, 'r', encoding='utf-8') as f:
            data = json.load(f)
        case_json = data['statistic']
        case_all = case_json['total']   # 测试用例总数
        case_fail = case_json['failed']     # 失败用例数量
        case_pass = case_json['passed']     # 成功用例数量
        if case_all >= 0:
            # 计算出来当前通过率
            case_rate = round((case_pass / case_all) * 100, 2)
        else:
            print('未获取到执行结果')

        #报告路径
        report_path= 'http://172.26.161.55:8888/job/SEM/%d/allure/' %self.job_num()

        #发送报告内容
        text = f"用例通过率：{case_rate}%" \
               f"\n执行用例数：{case_all}个"   \
                f"\n成功用例数：{case_pass}个" \
                f"\n失败用例数：{case_fail}个" \
                f"\n测试报告地址：{report_path}"
        data = {"msgtype":
                    "text",
                "text":
            {"content":"%s"%text},
                "at": {
                    # 要@的人
                    "atMobiles": [],
                    # 是否@所有人
                    "isAtAll": False
        }
                }
        url = 'https://oapi.dingtalk.com/robot/send?access_token=9dbd019634d4f1e5030bda612d2d322bddbddfa56077b4f5dc5a263b4f96e302'
        headers = {'Content-Type': 'application/json'}
        r = requests.post(url,headers=headers,data=json.dumps(data))
        print(r.status_code)





if __name__ == '__main__':
    send_ding().send_ding()